<template>
  <div class="home">
    <h1> User Home </h1>
    <div class="after-login">
      {{loginUser}}
      <button @click="exit">Exit</button>
    </div>

    <div class="goodsview">
      <SearchBar class="searchbar" @submit-like="onSubmitLike"/>
      <SearchType class="searchtype" @submit-type="onSubmitType"/>

      <div class="goodsgrid">
	<template v-for="goods in goodsList" :key="goods.id">
	  <Goods :goods="goods"/>
	</template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
 import { onMounted, ref } from 'vue';
 import {GoodsService, UserService} from '@/service'
 import { useRoute, useRouter } from 'vue-router';
 import SearchBar from '@/components/SearchBar.vue'
 import SearchType from '@/components/SearchType.vue'
 import Goods from '@/components/Goods.vue'
 const router = useRouter()
 const route = useRoute()
 const loginUser = ref('')
 const goodsList = ref<Array<Goods>>([])

 async function onSubmitLike(like: string) {
   goodsList.value = await GoodsService.findAll({
     like: like
   })
 }

 async function onSubmitType(type: string) {
   goodsList.value = await GoodsService.findAll({
     type: type
   })
 }

 async function exit() {
   let {message, data} = await UserService.exit()
   if(!data) {
     alert(message)
   } else {
     loginUser.value = ''
   }

   router.push('/')
 }

 onMounted(async () => {
   let {data} = await UserService.getLoginUser()
   if(data == null) {
     router.push({name: 'Home'})
     return
   }

   // loginUser.value = route.params['loginUser'] as string
   loginUser.value = data
   goodsList.value = await GoodsService.findAll()
 })
</script>

<style lang="scss" scoped>
 div.goodsview {
   display: grid;
   grid-template-areas:
     '. a a .'
     'b c c .'
     'b c c .'
     'b c c .';

   .searchbar {
     grid-area: a;
   }

   .searchtype {
     grid-area: b;
   }

   .goodsgrid {
     grid-area: c;
     border: 1px solid black;

     display: grid;
     grid-template-columns: repeat(2, 50%);
   }
 }
</style>